﻿using Flurl.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace RequestDemo
{
    class MechaAIHelper
    {
        private int m_ThreadDelay = 100;
        //  private static string m_InterfaceUrl = "http://192.168.10.200:20010";
        private static string m_InterfaceUrl = "http://192.168.9.4:20010";
        private static string m_ClientId = "SAM001";
        private static long m_RequestId;
        private static string templatename = "ED3-MP-IGBT-V1.0-L1";
        public MechaAIHelper(string[] param)
        {
            for (int i = 0; i < param.Length; i++)
            {
                if (param[i].StartsWith("InterfaceUrl="))
                {
                    string[] ss = param[i].Split('=');
                    m_InterfaceUrl = ss[1];
                }
                else if (param[i].StartsWith("ClientId="))
                {
                    string[] ss = param[i].Split('=');
                    m_ClientId = ss[1];
                }
            }
            m_RequestId = 0;
        }
        public static async void QueryTemplate()
        {
            m_RequestId++;
            Dictionary<string, string> headers = new Dictionary<string, string>()
            {
                {"Mode","queryargument" },//查询模板列表
                {"ClientId",m_ClientId },
                {"RequestId",m_RequestId.ToString() },
                {"Content-Type", "application/x-www-form-urlencoded" }//默认
            };
            var responseString = await m_InterfaceUrl
                                    .WithHeaders(headers, true)
                                    .PostAsync()
                                    .ReceiveString();
            Console.WriteLine(responseString);
        }
        public static async void ProcessImg()
        {
            m_RequestId++;
            Dictionary<string, string> headers = new Dictionary<string, string>()
            {
                {"Mode","calresult" },//图片计算
                {"ClientId",m_ClientId },
                {"RequestId",m_RequestId.ToString() },
                {"PicName","1" },
                {"TemplateName","MP-IN-MPFF600R12MBF-L501-V1" },
                { "Content-Type", "application/x-www-form-urlencoded" }//默认
        };
            Dictionary<string, string> img = new Dictionary<string, string>()
            {
                {"img",ImageToBase64(@"D:\MyStudy\NetDemo\RequestDemo\fail.tiff") }
            };
            var responseString = await m_InterfaceUrl
                                    .WithHeaders(headers, true)
                                    .PostUrlEncodedAsync(img)
                                    .ReceiveString();
            Console.WriteLine(responseString);
        }

        public static void switch_template2()
        {
            // templatename = "HP1-BYD-IGBT-V1.0-L0";
            templatename = "ED3-MP-IGBT-V1.0-L1";
            Dictionary<string, string> headers = new Dictionary<string, string>()
            {
                {"Clientid",m_ClientId },
                {"Requestid",m_RequestId.ToString() },
                 { "Content-Type", "application/json" },
                {"Templatename",templatename }
        };
            Dictionary<string, string> img = new Dictionary<string, string>()
            {
                {"img","" }
            };

            var url = m_InterfaceUrl + "/switch_template";

            //var responseString =  url
            //                        .WithHeaders(headers, true)
            //                        .PostUrlEncodedAsync(img)
            //                        .ReceiveString();

            Task<string> task = Task.Run(async () => await url
                                    .WithHeaders(headers, true)
                                    .PostUrlEncodedAsync(img)
                                    .ReceiveString());
            string responseString = task.Result;


            Console.WriteLine(responseString);
        }



        public static async void switch_template()
        {
            // templatename = "HP1-BYD-IGBT-V1.0-L0";
            templatename = "ED3-MP-IGBT-V1.0-L1";
            Dictionary<string, string> headers = new Dictionary<string, string>()
            {
                {"Clientid",m_ClientId },
                {"Requestid",m_RequestId.ToString() },
                 { "Content-Type", "application/json" },
                {"Templatename",templatename }
        };
            Dictionary<string, string> img = new Dictionary<string, string>()
            {
                {"img","" }
            };

            var url = m_InterfaceUrl + "/switch_template";

            var responseString = await url
                                    .WithHeaders(headers, true)
                                    .PostUrlEncodedAsync(img)
                                    .ReceiveString();
            Console.WriteLine(responseString);
        }
        public static void query_template()
        {
            templatename = "ED3-MP-IGBT-V1.0-L1";
            Dictionary<string, string> headers = new Dictionary<string, string>()
            {
                {"Clientid",m_ClientId },
                {"Requestid",m_RequestId.ToString() },
                 { "Content-Type", "application/json" },
                {"Templatename",templatename }
        };
            Dictionary<string, string> img = new Dictionary<string, string>()
            {
                {"img","" }
            };

            var url = m_InterfaceUrl + "/query_template";

            //var responseString = await url
            //                        .WithHeaders(headers, true)
            //                        .PostUrlEncodedAsync(img)
            //                        .ReceiveString();
            //Console.WriteLine(responseString);


            Task<string> task = Task.Run(async () => await url
                                    .WithHeaders(headers, true)
                                    .PostUrlEncodedAsync(img)
                                    //.PostAsync()
                                    .ReceiveString());
            string responseString = task.Result;


            Console.WriteLine(responseString);


        }
        public static async void query_result()
        {
            Dictionary<string, string> headers = new Dictionary<string, string>()
            {
                {"Clientid",m_ClientId },
                {"Requestid",m_RequestId.ToString() },
                 { "Content-Type", "application/json" },
                    {"Picname","22090122-Pass.tiff" },
                {"Templatename",templatename }
        };
            Dictionary<string, string> img = new Dictionary<string, string>()
            {
                {"img","" }
            };

            var url = m_InterfaceUrl + "/query_result";

            var responseString = await url
                                    .WithHeaders(headers, true)
                                    .PostUrlEncodedAsync(img)
                                    .ReceiveString();
            Console.WriteLine(responseString);
        }
        public static async void health_check()
        {
            Dictionary<string, string> headers = new Dictionary<string, string>()
            {
                {"Clientid",m_ClientId },
                {"Requestid",m_RequestId.ToString() },
                { "Content-Type", "application/json" }
        };
            Dictionary<string, string> img = new Dictionary<string, string>()
            {
                {"img","" }
            };

            var url = m_InterfaceUrl + "/health_check";

            var responseString = await url
                                    .WithHeaders(headers, true)
                                    .PostUrlEncodedAsync(img)
                                    .ReceiveString();
            Console.WriteLine(responseString);
        }

        public static void cal_result2()
        {
            var orgTiffFilePath = @"D:\MyStudy\NetDemo\RequestDemo\MP-IN-MPFF600R12MBFTEST-L1-V1-0005 20230802004129.tiff";
            // var orgTiffFilePath = @"D:\MyStudy\NetDemo\RequestDemo\fail.tiff";
            GetLayerRecord(orgTiffFilePath, out string errMsg);

        }




        public static DataTable GetLayerRecord(string aifilePath, out string errMsg)
        {
            DataTable m_ResultTable = new DataTable();
            errMsg = "";
            var model = "ED3-MP-IGBT-V1.0-L1";
            m_RequestId++;
            Dictionary<string, string> headers = new Dictionary<string, string>()
            {
               // {"Mode","queryresult" },//查询结果
                {"ClientId",m_ClientId },
                {"RequestId",m_RequestId.ToString() },
                {"PicName",Path.GetFileName(aifilePath) },
                {"TemplateName",model },
                 { "Content-Type", "application/json" },
               // {"Content-Type", "application/x-www-form-urlencoded" }//默认
             };
            Dictionary<string, string> img = new Dictionary<string, string>()
            {
                {"img","" }
            };

            var apiUrl = m_InterfaceUrl + "/query_result";
            int retryCount = 1000;
            JObject jos = null; ;
            JObject jo;
            while (retryCount >= 0)
            {
                //Task<string> responseString = apiUrl
                //          .WithHeaders(headers, true)
                //          .PostUrlEncodedAsync(img)
                //          .ReceiveString();

                Task<string> responseString = Task.Run(async () => await apiUrl
                                   .WithHeaders(headers, true)
                                   .PostUrlEncodedAsync(img)
                                   .ReceiveString());

                Console.WriteLine(responseString);

                while (!responseString.IsCompleted)
                {
                    Thread.Sleep(100);
                }
                Console.WriteLine(responseString);
                if (responseString.Status == TaskStatus.Faulted)
                {
                    errMsg = $"AI查询模型ROI计算值失败,{responseString.Exception.InnerExceptions}";
                    return null;
                }
                retryCount--;

                if (string.IsNullOrEmpty(responseString.Result))
                {
                    Thread.Sleep(100);
                    continue;
                }
                else
                {
                    jos = JObject.Parse(responseString.Result);
                    if (jos == null)
                    {
                        errMsg = $"AI查询模型ROI计算值失败,{responseString.Result}";
                        return null;
                    }

                    string Data = jos["message"].ToString();
                    var list = JsonConvert.DeserializeObject<List<AiResult>>(Data);
                    if ((int)jos["errorcode"] == 0 && list.Where(i => i.quality == 2).Count() > 0)//正在处理
                    {
                        Thread.Sleep(100);
                        continue;
                    }
                    else
                    {
                        break;
                    }



                }
            }
            if (retryCount < 0)
            {
                errMsg = $"AI查询模型ROI计算值失败,查询超时";
                return null;
            }

            if ((int)jos["errorcode"] == 0)
            {
                jo = jos["message"] as JObject;
                string data = jos["message"].ToString();
                var list = JsonConvert.DeserializeObject<List<AiResult>>(data);
                foreach (var a in list)
                {
                    DataRow dr = m_ResultTable.NewRow();
                    dr["quality"] = a.quality;
                    dr["defect_ratio"] = a.defect_ratio;
                    dr["pic_name"] = a.pic_name;
                    dr["area_no"] = a.detect_time;
                    dr["roi_name"] = a.roi_name;
                    dr["single_defect_ratio"] = a.single_defect_ratio;
                    dr["template_name"] = a.template_name;
                    m_ResultTable.Rows.Add(dr);
                }
            }
            else
            {
                string errorDesc = ((string)jos["errorcode"]);
                errMsg = $"AI查询模型ROI计算值失败,{errorDesc}";
            }
            m_ResultTable.AcceptChanges();
            return m_ResultTable;
        }




        public static async void cal_result1()
        {
            var orgTiffFilePath = @"D:\MyStudy\NetDemo\RequestDemo\MP-IN-MPFF600R12MBFTEST-L1-V1-0005 20230802004129.tiff";
            // var orgTiffFilePath = @"D:\MyStudy\NetDemo\RequestDemo\fail.tiff";
            var model = "ED3-MP-IGBT-V1.0-L1";
            m_RequestId++;
            //Dictionary<string, string> headers = new Dictionary<string, string>()
            //{
            //    {"Mode","calresult" },//图片计算
            //    {"ClientId",m_ClientId },
            //    {"RequestId",m_RequestId.ToString() },
            //    {"PicName",Path.GetFileNameWithoutExtension(orgTiffFilePath) },
            //    {"TemplateName",model },
            //    { "Content-Type", "application/x-www-form-urlencoded" }//默认
            //};

            Dictionary<string, string> headers = new Dictionary<string, string>()
            {
                {"ClientId",m_ClientId },
                {"RequestId",m_RequestId.ToString() },
                 { "Content-Type", "application/json" },//默认
                {"PicName",Path.GetFileName(orgTiffFilePath) },
                {"TemplateName",model }

        };

            Dictionary<string, string> json = new Dictionary<string, string>()
            {
                {"img",ImageToBase64(orgTiffFilePath) }
            };

            string jsonStr = JsonConvert.SerializeObject(json);

            var apiUrl = m_InterfaceUrl + "/cal_result";

            //m_InterfaceUrl.WithHeaders(headers, true)
            //             .PostUrlEncodedAsync(img);

            //apiUrl.WithHeaders(headers, true)
            //         .PostUrlEncodedAsync(jsonStr);

            var responseString22 = await apiUrl
                                 .WithHeaders(headers, true)
                                 .PostStringAsync(jsonStr)
                                 .ReceiveString();


            Task<string> responseString = Task.Run(async () => await apiUrl
                                    .WithHeaders(headers, true)
                                    .PostStringAsync(jsonStr)
                                    .ReceiveString());

            while (!responseString.IsCompleted)
            {
                Thread.Sleep(100);
            }

            var kk = responseString.Result;


            //    Dictionary<string, string> headers = new Dictionary<string, string>()
            //    {
            //        {"Clientid",m_ClientId },
            //        {"Requestid",m_RequestId.ToString() },
            //         { "Content-Type", "application/json" },//默认
            //        {"Picname","22090122-Pass.tiff" },
            //        {"Templatename",templatename }

            //};
            //    Dictionary<string, string> json = new Dictionary<string, string>()
            //    {
            //        {"img",ImageToBase64(@"D:\MyStudy\NetDemo\RequestDemo\22090122-Pass.tiff") }
            //    };

            //    string jsonStr = JsonConvert.SerializeObject(json);

            //    var url = m_InterfaceUrl + "/cal_result";

            //    var responseString = await url
            //                            .WithHeaders(headers, true)
            //                            .PostStringAsync(jsonStr)
            //                            .ReceiveString();
            //    Console.WriteLine(responseString);
            //    var orgTiffFilePath = @"D:\MyStudy\NetDemo\RequestDemo\MP-IN-MPFF600R12MBFTEST-L1-V1-0005 20230802004129.tiff";
            //    // var orgTiffFilePath = @"D:\MyStudy\NetDemo\RequestDemo\fail.tiff";
            //    var model = "ED3-MP-IGBT-V1.0-L1";
            //    m_RequestId++;
            //    //Dictionary<string, string> headers = new Dictionary<string, string>()
            //    //{
            //    //    {"Mode","calresult" },//图片计算
            //    //    {"ClientId",m_ClientId },
            //    //    {"RequestId",m_RequestId.ToString() },
            //    //    {"PicName",Path.GetFileNameWithoutExtension(orgTiffFilePath) },
            //    //    {"TemplateName",model },
            //    //    { "Content-Type", "application/x-www-form-urlencoded" }//默认
            //    //};

            //    Dictionary<string, string> headers = new Dictionary<string, string>()
            //    {
            //        {"ClientId",m_ClientId },
            //        {"RequestId",m_RequestId.ToString() },
            //         { "Content-Type", "application/json" },//默认
            //        {"PicName",Path.GetFileNameWithoutExtension(orgTiffFilePath) },
            //        {"TemplateName",model }

            //};

            //    Dictionary<string, string> json = new Dictionary<string, string>()
            //    {
            //        {"img",ImageToBase64(orgTiffFilePath) }
            //    };

            //    string jsonStr = JsonConvert.SerializeObject(json);

            //    var apiUrl = m_InterfaceUrl + "/cal_result";

            //    //m_InterfaceUrl.WithHeaders(headers, true)
            //    //             .PostUrlEncodedAsync(img);

            //    //apiUrl.WithHeaders(headers, true)
            //    //         .PostUrlEncodedAsync(jsonStr);

            //    var responseString22 = await apiUrl
            //                         .WithHeaders(headers, true)
            //                         .PostStringAsync(jsonStr)
            //                         .ReceiveString();


            //    Task<string> responseString = Task.Run(async () => await apiUrl
            //                            .WithHeaders(headers, true)
            //                            .PostStringAsync(jsonStr)
            //                            .ReceiveString());

            //    while (!responseString.IsCompleted)
            //    {
            //        Thread.Sleep(100);
            //    }

            //    var kk = responseString.Result;

            // string responseString = task.Result;
        }


        public static async void cal_result()
        {

            var orgTiffFilePath = @"D:\MyStudy\NetDemo\RequestDemo\MP-IN-MPFF600R12MBFTEST-L1-V1-0005 20230802004129.tiff";


            Dictionary<string, string> headers = new Dictionary<string, string>()
            {
                {"Clientid",m_ClientId },
                {"Requestid",m_RequestId.ToString() },
                 { "Content-Type", "application/json" },//默认
                {"Picname",Path.GetFileName(orgTiffFilePath) },
                {"Templatename",templatename }

        };
            Dictionary<string, string> json = new Dictionary<string, string>()
            {
                {"img",ImageToBase64(orgTiffFilePath) }
            };

            string jsonStr = JsonConvert.SerializeObject(json);

            var url = m_InterfaceUrl + "/cal_result";

            var responseString = await url
                                    .WithHeaders(headers, true)
                                    .PostStringAsync(jsonStr)
                                    .ReceiveString();
            Console.WriteLine(responseString);
        }


        private static async void QueryImgResult()
        {
            m_RequestId++;
            Dictionary<string, string> headers = new Dictionary<string, string>()
            {
                {"Mode","queryresult" },//查询结果
                {"ClientId",m_ClientId },
                {"RequestId",m_RequestId.ToString() },
                {"PicName","1" },
                {"TemplateName","MP-IN-MPFF600R12MBF-L501-V1" },
                {"Content-Type", "application/x-www-form-urlencoded" }//默认
             };
            Dictionary<string, string> img = new Dictionary<string, string>()
            {
                {"img","" }
            };
            var responseString = await m_InterfaceUrl
                                    .WithHeaders(headers, true)
                                    .PostUrlEncodedAsync(img)
                                    .ReceiveString();
            Console.WriteLine(responseString);
        }
        public static string ImageToBase64(string fileFullName)
        {
            try
            {
                byte[] bytes = File.ReadAllBytes(fileFullName);
                return Convert.ToBase64String(bytes);
            }
            catch (Exception ex)
            {
                return null;
            }
        }


        public bool UnInitConn(out string errMsg)
        {
            errMsg = "";
            return true;
        }

        private string GetErrorDesc(int v1, int v2)
        {
            string code = $"{v1}{v2}";
            switch (code)
            {
                case "00":
                    return "No Error";
                case "01":
                    return "图片解码异常";
                case "10":
                    return "服务程序错误";
                default:
                    return $"未知错误 {code}";
            }
        }


        public int GetSubUnitIndexByROI(string roi_name)
        {
            int subUnitIndexPos = -1;// roi_name.IndexOf("_");
            int roi_name_Index = roi_name.IndexOf("_", subUnitIndexPos + 1);
            string subUnitIndexStr = roi_name.Substring(subUnitIndexPos + 1, roi_name_Index - subUnitIndexPos);
            int subUnitIndex = int.Parse(subUnitIndexStr.Replace("N", "")) - 1;
            return subUnitIndex;
        }


        private string m_CurrentPic = null;

    }
}
